package com.whut.mobilesafe.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.whut.mobilesafe.R;
import com.whut.mobilesafe.db.dao.BlackListDao;
import com.whut.mobilesafe.domain.BlackListInFo;
import com.whut.mobilesafe.viewholder.ListItemBlackHolder;

import java.util.ArrayList;

/**
 * 作    者:yubo.xiaoyubo
 * 时    间：2015/12/25 8:26
 * 版    本：1.0
 * 描    述： 黑名单管理 开发流程:
 * 1. 布局文件
 * 2. 封装黑名单数据库
 * 3. listview填充数据
 * 4. listview优化
 * 5. 在子线程加载数据
 * 6.异步加载黑名单数据
 * 7.分页加载(1.使用limit语句查询一页数据 2. 展示第一页数据 3. 监听滑动到底部的事件 4.加载下一页数据,5.判断是否到最后一页)
 * 8.添加黑名单
 * 9. 删除黑名单
 */
public class BlackListActivity extends Activity {

    /**
     * black_list_dialog 中的控件
     */
    private Button btnAdd;
    private Button btnCancel;
    private EditText etBlackNumber;
    private RadioGroup rgRoot;

    private BlackListDao mDao;
    private ArrayList<BlackListInFo> mInFos;
    private Adapter mAdapter;
    private ListView lvBlackList;
    private ProgressBar pbLoading;

    private ListItemBlackHolder mHolder;
    private int mIndex=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_black_list);
        lvBlackList = (ListView) findViewById(R.id.lv_black_list);
        pbLoading = (ProgressBar)findViewById(R.id.pb_loading);

        //初始化数据
        initData();
        lvBlackList.setOnScrollListener(new AbsListView.OnScrollListener() {
            //当滑动状态改变的时候回调
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //如过此时没有滑动的话，判断是否是滑倒最低了，如果是最低还有没有数据
                if(scrollState == SCROLL_STATE_IDLE){
                    //获取当前页最后一条的位置
                    int lastVisiblePosition = lvBlackList.getLastVisiblePosition();
                    if(lastVisiblePosition >= mInFos.size()-1) {
                        int total = mDao.getCount();
                        if(mInFos.size() < total){
                            initData();
                        }else {
                            Toast.makeText(BlackListActivity.this, "没有更多数据了哦", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
            //当滑动的过程中回调
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    private void initData() {
        pbLoading.setVisibility(View.VISIBLE);

        new Thread() {
            @Override
            public void run() {
                try {
                    //模拟延时
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                mDao = BlackListDao.getInstance(getApplicationContext());
                //下面开始分页查询
                //mInFos = mDao.queryAll();
                if(mInFos == null){
                    mInFos = mDao.pageQuery(mIndex);
                }else{
                    // 在原有集合上追加20条数据
                    ArrayList<BlackListInFo> partInFos = mDao.pageQuery(mIndex);
                    mInFos.addAll(partInFos);
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(mAdapter == null){
                            mAdapter = new Adapter();
                            lvBlackList.setAdapter(mAdapter);
                        }else{
                            mAdapter.notifyDataSetChanged();
                        }

                        mIndex=mInFos.size();
                        // 隐藏进度条
                        pbLoading.setVisibility(View.GONE);
                    }
                });
            }
        }.start();
    }


    class Adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mInFos.size();
        }

        @Override
        public BlackListInFo getItem(int position) {
            return mInFos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                mHolder = new ListItemBlackHolder();
                convertView = View.inflate(getApplicationContext(), R.layout.list_item_black, null);
                mHolder.tvBlackNumber = (TextView) convertView.findViewById(R.id.tv_black_number);
                mHolder.tvType = (TextView) convertView.findViewById(R.id.tv_type);
                mHolder.ibClear = (ImageButton) convertView.findViewById(R.id.ib_clear);
                convertView.setTag(mHolder);
            } else {
                mHolder= (ListItemBlackHolder) convertView.getTag();
            }
            final BlackListInFo inFo = getItem(position);
            mHolder.tvBlackNumber.setText(inFo.getNumber());
            switch (inFo.getMode()) {
                case 1:
                    mHolder.tvType.setText("拦截电话");
                    break;
                case 2:
                    mHolder.tvType.setText("拦截短信");
                    break;
                case 3:
                    mHolder.tvType.setText("拦截全部");
                    break;
            }
            mHolder.ibClear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 1.从数据库删除
                    // 2.从集合删除
                    // 3.刷机listview
                    mDao.delete(inFo.getNumber());
                    mInFos.remove(inFo);
                    //其实是删除了，但是页面没有刷新
                    mAdapter.notifyDataSetChanged();
                }
            });
            return convertView;
        }
    }

    //点击添加按钮的时候，这个时候弹出对话框，让用户选择添加的号码等信息
    public void add(View view) {
        showAddBlackListDialog();
    }

    private void showAddBlackListDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.black_list_dialog, null);

        btnAdd = (Button) view.findViewById(R.id.btn_add);
        btnCancel = (Button) view.findViewById(R.id.btn_cancel);
        etBlackNumber = (EditText) view.findViewById(R.id.et_black_number);
        rgRoot = (RadioGroup) view.findViewById(R.id.rg_root);

        dialog.setView(view, 0, 0, 0, 0);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击添加按钮之后,1.将数据添加至数据库，和集合然后通知listView 数据改变了
                String blackNumber = etBlackNumber.getText().toString();
                if (!TextUtils.isEmpty(blackNumber)) {
                    int mode = 1;
                    switch (rgRoot.getCheckedRadioButtonId()) {
                        case R.id.rb_phone:
                            mode = 1;
                            break;
                        case R.id.rb_message:
                            mode = 2;
                            break;
                        case R.id.rb_all:
                            mode = 3;
                            break;
                    }

                    // 保存到黑名单数据库中
                    mDao.add(blackNumber,mode);
                    // 给集合添加元素
                    BlackListInFo info = new BlackListInFo(blackNumber,mode);
                    mInFos.add(0,info);
                    // 刷新界面（通知数据发生变化）
                    mAdapter.notifyDataSetChanged();
                    dialog.dismiss();
                } else {
                    Toast.makeText(BlackListActivity.this, "添加号码不能为空哟", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
    }
}
